/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.opprua.tidy.conversion;

import java.util.HashMap;
import java.util.Map;

import org.opprua.tidy.util.Primitives;

/**
 * TODO: add Java doc
 * 
 * Prepared for first commit: 15.07.2007
 * 
 * @author Lin Li
 */
public class ChangerBroker {

  private static Map<Class<?>, Changer<?>> seeds = new HashMap<Class<?>, Changer<?>>();

  static {
    setupChangers();
  }

  private ChangerBroker() {
  }

  @SuppressWarnings("unchecked")
  private static void setupChangers() {
    ChangerBroker.setChanger(new CTBool());
    ChangerBroker.setChanger(new CTByte());
    ChangerBroker.setChanger(new CTChar());
    ChangerBroker.setChanger(new CTDate());
    ChangerBroker.setChanger(new CTDataBaseDate());
    ChangerBroker.setChanger(new CTDouble());
    ChangerBroker.setChanger(new CTFloat());
    ChangerBroker.setChanger(new CTInt());
    ChangerBroker.setChanger(new CTLong());
    ChangerBroker.setChanger(new CTShort());
    ChangerBroker.setChanger(new CTString());
    ChangerBroker.setChanger(new CTTime());
    ChangerBroker.setChanger(new CTTimestamp());
  }

  public synchronized static <T> void setChanger(Changer<T> s) {
    seeds.put(s.getType(), s);
  }

  @SuppressWarnings("unchecked")
  public synchronized static <T> Changer<T> getFor(Class<T> to) {
    return (Changer<T>) seeds.get(Primitives.getWrapperFor(to));
  }

  /**
   */
  @SuppressWarnings("unchecked")
  public static <T> T getDefaultValue(Class<T> c) {
    Changer<T> ger = getFor(c);
    if (ger == null) return null;
    return ger.getDefaultValue();
  }

  /**
   */
  @SuppressWarnings("unchecked")
  public static <T> T convert(Class<T> c, Object o) {
    if (o != null && Primitives.getWrapperFor(c).isAssignableFrom(o.getClass())) return (T) o;

    Changer<T> s = getFor(c);
    if (s == null || o == null) return null;
    return s.get(o);
  }
}
